/* eslint-disable @typescript-eslint/no-explicit-any */

import { customRef } from "vue";

/**
 * @description 防抖函数
 * @param {Function} func 需要防抖的函数
 * @param {number} wait 防抖时间
 * @param immediate 是否立即执行
 * @returns
 */
export function debounce(
  func: (...args: any[]) => void,
  wait: number,
  immediate = false,
) {
  let timeout: NodeJS.Timeout;
  return function (...args: any[]) {
    if (immediate) {
      func(...args);
    }
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      if (!immediate) {
        func(...args);
      }
    }, wait);
  };
}

/**
 * 导出一个函数，用于创建一个防抖的ref
 * @refrence https://cn.vuejs.org/api/reactivity-advanced.html#customref
 */
export function useDebouncedRef(value: any, delay = 200) {
  let timeout: NodeJS.Timeout;
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value;
      },
      set(newValue) {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          value = newValue;
          trigger();
        }, delay);
      },
    };
  });
}
